<?php

namespace App\ServicesNew\Impl;

use App\Entities\ConvertibleCardSaleRecordEntity;
use App\Entities\OrderEntity;
use App\Entities\PaymentEntity;
use App\Entities\PaymentModel;
use App\Entity\UserEntity;
use App\ServicesNew\PaymentService;

class PaymentServiceImpl implements PaymentService
{
    /**
     * @inheritDoc
     */
    public function getUserEntityByPayment(PaymentEntity $paymentEntity)
    {
        $userId = 0;
        $tradeNo = $paymentEntity->getTradeNo();
        switch ($paymentEntity->getOrderType()) {
            case PaymentModel::ORDER_TYPE_CLEAN_SERVICE:
                $orderEntity = OrderEntity::findByTradeNo($tradeNo);
                if (!is_null($orderEntity)) {
                    $userId = $orderEntity->getUserId();
                }
                break;
            case PaymentModel::ORDER_TYPE_CONVERTIBLE_CARD:
                $convertibleCardSaleRecordEntity = ConvertibleCardSaleRecordEntity::findByTradeNo($tradeNo);
                if (!is_null($convertibleCardSaleRecordEntity)) {
                    $userId = $convertibleCardSaleRecordEntity->getUserId();
                }
                break;
        }

        return $userId > 0 ? UserEntity::find($userId) : null;
    }
}
